/*
 * @Author: 王欣磊
 * @Date: 2024-07-12 17:47:35
 * @LastEditors: 王欣磊
 * @LastEditTime: 2024-09-18 16:16:41
 * @Description: 文件相关的工具函数
 * @FilePath: /safe-platform-ui/src/utils/file.js
 */
const KKFILEVIEW_API_PATH = process.env.VUE_APP_KKFILEVIEW_API;
import { Base64 } from "js-base64";
import guid from "./guid";
import { getFileGeneratePreviewUrl } from "@/api/file/file";

/**
 * 打开KK文件预览
 * @param {string} url - 文件的URL
 * @returns {string} - KK文件预览的URL
 */
export function getKKFilePreviewUrl(url) {
  return new Promise(async (resolve, reject) => {
    // TODO:多个的情况（逗号分割），采用多图预览模式，多文件预览暂不支持，待设计
    if (url.includes(",")) {
      const fileUrls = url.replace(/,/g, "|");
      const urlEncoded = encodeURIComponent(Base64.encode(fileUrls));
      resolve(`${KKFILEVIEW_API_PATH}/picturesPreview?urls=${urlEncoded}`);
    }
    // 单个的情况，采用在线预览文件模式
    else {
      const res = await getFileGeneratePreviewUrl({ fileUrl: url });
      if (res.code === 200 && res.data?.previewUrl) {
        const resUrl = res.data.previewUrl;
        const urlEncoded = encodeURIComponent(Base64.encode(resUrl));
        resolve(`${KKFILEVIEW_API_PATH}/onlinePreview?url=${urlEncoded}`);
      } else {
        const haveSuffix = url.match(/\.\w+$/);

        const urlEncoded = encodeURIComponent(
          Base64.encode(
            url + (haveSuffix ? "" : `&fullfilename=${guid(16)}.jpg`)
          )
        );

        resolve(`${KKFILEVIEW_API_PATH}/onlinePreview?url=${urlEncoded}`);
      }
    }
  });
}
